package com.ruoyi.base.schedule;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.base.domain.BaseTask;
import com.ruoyi.base.service.IBaseTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Random;

@Component
public class TaskAllocation {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IBaseTaskService baseTaskService;
    public void taskAllocate(){

        List<Long> taskList = (List<Long>) redisTemplate.opsForValue().get("taskQueue");
        if(taskList.isEmpty())
            return;
        List<Long> list = (List<Long>) redisTemplate.opsForValue().get("onlineForkliftQueue");
        if(list.isEmpty())
            return;
        List<Long> workList = (List<Long>) redisTemplate.opsForValue().get("workForkliftQueue");

        Long taskId = taskList.remove(0);
        LambdaQueryWrapper<BaseTask> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BaseTask::getId,taskId);
        BaseTask baseTask = baseTaskService.getOne(lqw);
        if(ObjectUtil.isNull(baseTask))
            return;

        Random random = new Random();
        int index = random.nextInt(list.size());
        Long supplierId = list.get(index);


        //将叉车从空闲列表移除
        list.removeIf(value->value==supplierId);
        redisTemplate.opsForValue().set("onlineForkliftQueue",list);
        workList.add(supplierId);
        redisTemplate.opsForValue().set("workForkliftQueue",list);
        //修改任务数据
        baseTask.setSupperId(supplierId);
        baseTaskService.updateById(baseTask);
    }
}
